#!/usr/bin/env node

/**
 * 修复admin表中linkedUserId字段的引号问题
 */

const AdminModel = require('./model/admin_model.js');

async function fixLinkedUserIdQuotes() {
    try {
        console.log('=== 修复admin表中linkedUserId字段的引号问题 ===');
        
        const userId = 'oPOlNvkKFRjdTazLzUq6D2sHunp0'; // 正确的用户ID
        const quotedUserId = `"${userId}"`; // 带引号的用户ID（错误格式）
        
        console.log('正确的用户ID:', userId);
        console.log('错误的用户ID（带引号）:', quotedUserId);
        
        // 查找所有admin记录
        const allAdmins = await AdminModel.getList({}, 'ADMIN_ID,ADMIN_NAME,linkedUserId,ADMIN_STATUS,isActive');
        
        console.log('\n所有admin记录:');
        allAdmins.forEach((admin, index) => {
            console.log(`${index + 1}. Admin ID: ${admin.ADMIN_ID}`);
            console.log(`   Admin Name: ${admin.ADMIN_NAME}`);
            console.log(`   Linked User ID: ${admin.linkedUserId || '未关联'}`);
            console.log(`   Linked User ID 类型: ${typeof admin.linkedUserId}`);
            console.log(`   Linked User ID 长度: ${admin.linkedUserId ? admin.linkedUserId.length : 0}`);
            console.log(`   Admin Status: ${admin.ADMIN_STATUS}`);
            console.log(`   Is Active: ${admin.isActive}`);
            console.log('---');
        });
        
        // 查找有问题的admin记录（linkedUserId包含引号）
        const problematicAdmin = await AdminModel.getOne({
            linkedUserId: quotedUserId
        });
        
        if (problematicAdmin) {
            console.log('\n✅ 找到有问题的admin记录:');
            console.log('Admin ID:', problematicAdmin.ADMIN_ID);
            console.log('当前linkedUserId:', problematicAdmin.linkedUserId);
            console.log('linkedUserId类型:', typeof problematicAdmin.linkedUserId);
            
            // 修复linkedUserId字段
            await AdminModel.edit({
                ADMIN_ID: problematicAdmin.ADMIN_ID
            }, {
                linkedUserId: userId, // 移除引号
                ADMIN_EDIT_TIME: Date.now()
            });
            
            console.log('✅ linkedUserId字段已修复');
            
            // 验证修复结果
            const fixedAdmin = await AdminModel.getOne({
                ADMIN_ID: problematicAdmin.ADMIN_ID
            });
            
            console.log('修复后的linkedUserId:', fixedAdmin.linkedUserId);
            console.log('修复后类型:', typeof fixedAdmin.linkedUserId);
        } else {
            console.log('\n❌ 未找到有问题的admin记录');
            
            // 尝试直接查找正确的用户ID
            const correctAdmin = await AdminModel.getOne({
                linkedUserId: userId
            });
            
            if (correctAdmin) {
                console.log('✅ 找到正确的admin记录:');
                console.log('Admin ID:', correctAdmin.ADMIN_ID);
                console.log('Linked User ID:', correctAdmin.linkedUserId);
            } else {
                console.log('❌ 未找到任何关联的admin记录');
            }
        }
        
        // 最终验证
        console.log('\n=== 最终验证 ===');
        const finalAdmin = await AdminModel.getOne({
            linkedUserId: userId,
            ADMIN_STATUS: 1,
            isActive: true
        }, 'ADMIN_ID,ADMIN_NAME,ADMIN_TYPE,linkedUserId,permissions,role');
        
        if (finalAdmin) {
            console.log('✅ 验证成功：用户已正确关联到admin账号');
            console.log('Admin信息:', {
                adminId: finalAdmin.ADMIN_ID,
                adminName: finalAdmin.ADMIN_NAME,
                linkedUserId: finalAdmin.linkedUserId,
                role: finalAdmin.role,
                permissions: finalAdmin.permissions
            });
        } else {
            console.log('❌ 验证失败：用户未正确关联');
        }
        
        console.log('\n=== 修复完成 ===');
        
        return {
            success: true,
            message: 'linkedUserId引号问题修复完成',
            userId: userId
        };
        
    } catch (error) {
        console.error('❌ 修复失败:', error);
        return {
            success: false,
            message: '修复失败: ' + error.message
        };
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    fixLinkedUserIdQuotes().then(result => {
        console.log('修复结果:', result);
        process.exit(result.success ? 0 : 1);
    }).catch(error => {
        console.error('脚本执行失败:', error);
        process.exit(1);
    });
}

module.exports = { fixLinkedUserIdQuotes };
